<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { systemApi } from '@/api'
import { ElMessage } from 'element-plus'
import { PHONE_REG, NUMBER_OR_ENGLISH_REG } from '@/utils'
const router = useRouter()
const route = useRoute()
const loading = ref(false)
const refForm = ref()
const id = computed(() => route.query.id || '')
const roleOptions = ref([])
const ruleForm = ref({
  roleId: '',
  contacts: '',
  department: '',
  userPhone: '',
  loginName: '',
  password: '',
  src: ''
})
const rules = ref({
  roleId: [{ required: true, message: '请选择角色', trigger: 'blur' }],
  contacts: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  department: [{ required: true, message: '请输入部门名称', trigger: 'blur' }],
  userPhone: [
    { required: true, message: '请输入手机号', trigger: 'change' },
    { pattern: PHONE_REG, trigger: 'change', message: '请输入正确的手机号' }
  ],
  loginName: [
    { required: true, message: '请输入账号', trigger: 'change' },
    {
      pattern: NUMBER_OR_ENGLISH_REG,
      message: '请输入英文或数字',
      trigger: 'change'
    }
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'change'
    },
    {
      pattern: /[0-9a-zA-Z]{6,16}$/,
      message: '请输入长度6-16位的密码，支持数字、字母',
      trigger: ['blur', 'change']
    }
  ]
})
onMounted(() => {
  getAllRoles()
  if (id.value) {
    getAdminUserDetail()
  }
})
// 获取详情
async function getAdminUserDetail() {
  const { data } = await systemApi.default.querySysUser({
    id: id.value
  })
  ruleForm.value = data
}

// 查询主场的所有角色
async function getAllRoles() {
  const { data } = await systemApi.default.getHomeAllRole()
  roleOptions.value = data
}

async function submitForm() {
  await refForm.value.validate()
  loading.value = true
  id.value ? editAdminUser() : addAdminUser()
}

// 编辑
async function editAdminUser() {
  try {
    await systemApi.default.updateSysUser(ruleForm.value)
    loading.value = false
    ElMessage.success('编辑成功')
    goBack()
  } catch (error) {
    loading.value = false
  }
}

// 新增
async function addAdminUser() {
  try {
    await systemApi.default.addSysUser(ruleForm.value)
    loading.value = false
    ElMessage.success('新增成功')
    goBack()
  } catch (error) {
    loading.value = false
  }
}

function goBack() {
  router.back()
}
</script>

<template>
  <div>
    <el-card shadow="never">
      <el-page-header
        :content="id ? '编辑用户信息' : '新增管理员用户'"
        @back="goBack"
      ></el-page-header>
    </el-card>
    <el-card shadow="never">
      <el-form
        ref="refForm"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
        label-suffix="："
        label-position="left"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="contacts">
              <el-input v-model="ruleForm.contacts" clearable></el-input>
            </el-form-item>
            <el-form-item label="部门" prop="department">
              <el-input v-model="ruleForm.department" clearable></el-input>
            </el-form-item>
            <el-form-item label="角色" prop="roleId">
              <el-select v-model="ruleForm.roleId" placeholder="请选择">
                <el-option
                  v-for="item in roleOptions"
                  :key="item.id"
                  :label="item.roleName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="手机号" prop="userPhone">
              <el-input v-model.trim="ruleForm.userPhone" clearable />
            </el-form-item>
            <el-form-item label="账号" prop="loginName">
              <el-input v-model.trim="ruleForm.loginName" clearable />
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model.trim="ruleForm.password" show-password />
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <DeUpload v-model="ruleForm.src" />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" :loading="loading" @click="submitForm">
                立即提交
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>
